﻿using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV.Util;
using Emgu.CV;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsApp1
{
    public class WhiteRegionDetector
    {
        /// <summary>
        /// 查找接近白色的连续区域（面积≥5像素）
        /// </summary>
        /// <param name="imagePath">输入图像路径</param>
        /// <param name="minArea">最小区域面积（默认5像素）</param>
        /// <returns>检测到的区域边界框列表</returns>
        public static List<Rectangle> FindNearWhiteRegions(string imagePath, int minArea = 3)
        {
            List<Rectangle> result = new List<Rectangle>();

            // 1. 加载图像
            using (Mat src = CvInvoke.Imread(imagePath, ImreadModes.Color))
            {
                if (src.IsEmpty)
                    throw new ArgumentException("无法加载图像");

                // 2. 转换为HSV颜色空间
                Mat hsv = new Mat();
                CvInvoke.CvtColor(src, hsv, ColorConversion.Bgr2Hsv);

                // 3. 定义白色范围（HSV: 低饱和度，高亮度）
                ScalarArray lower = new ScalarArray(new MCvScalar(10,40, 180)); // H:0-180, S:0-255, V:0-255
                ScalarArray upper = new ScalarArray(new MCvScalar(30, 60, 220));

                // 4. 创建颜色掩码
                Mat mask = new Mat();
                CvInvoke.InRange(hsv, lower, upper, mask);

                // 5. 形态学操作（可选：去除噪声）
                Mat kernel = CvInvoke.GetStructuringElement(ElementShape.Rectangle, new Size(3, 3), new Point(-1, -1));
                CvInvoke.MorphologyEx(mask, mask, MorphOp.Open, kernel, new Point(-1, -1), 1, BorderType.Default, default);

                // 6. 查找轮廓
                VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
                CvInvoke.FindContours(mask, contours, null, RetrType.List, ChainApproxMethod.ChainApproxSimple);

                // 7. 筛选轮廓
                for (int i = 0; i < contours.Size; i++)
                {
                    double area = CvInvoke.ContourArea(contours[i]);
                    if (area >= minArea)
                    {
                        Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);
                        result.Add(rect);
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 可视化检测结果
        /// </summary>
        public static void VisualizeResult(string inputPath, string outputPath, List<Rectangle> regions)
        {
            using (Mat src = CvInvoke.Imread(inputPath))
            {
                foreach (var rect in regions)
                {
                    CvInvoke.Rectangle(src, rect, new MCvScalar(0, 255, 0), 2);
                }
                CvInvoke.Imwrite(outputPath, src);
            }
        }

        // 使用示例
        public static void Main3(string b)
        {
            try
            {
                string input = b;
                string output = "output.jpg";

                var regions = FindNearWhiteRegions(input);
                VisualizeResult(input, output, regions);

                Console.WriteLine($"检测到 {regions.Count} 个白色区域");
                Console.WriteLine("结果已保存至: " + output);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }
    }
}
